//
//  DBData.m
//  exhibition
//
//  Created by thomas on 13-9-3.
//  Copyright (c) 2013年 thomas. All rights reserved.
//

#import "DBData.h"
#import "Sqlite.h"
#define IsTb(x,y) [y isEqualToString:x]

@implementation DBData

+ (void)resetdatabase{
    [SqlightAdapter database:dbName AndTable:nil];
}
+ (NSMutableArray*)tbInfo:(NSString*)tbName
{
    if(IsTb(tbName,tb_beacon)){
        return [NSMutableArray arrayWithObjects:
                @"id INTEGER NOT NULL PRIMARY KEY",@"likeid INTEGER",
                @"b_mac",@"b_name",@"b_mm",@"b_uuid",@"g_name",@"xy",@"status INTEGER NOT NULL DEFAULT 0",@"localtime DATETIME  DEFAULT (datetime('now','localtime'))",nil];
    }

    /*else if(IsTb(tbName,tb_dataForUser)){
        return [NSMutableArray arrayWithObjects:
                @"sid VARCHAR(100) NOT NULL  PRIMARY KEY",
                @"name",
                @"point",
                @"px Double NOT NULL DEFAULT NULL",
                @"py Double NOT NULL DEFAULT NULL",
                @"status INTEGER NOT NULL DEFAULT 0",
//                @"id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT",
//                @"type INTEGER NOT NULL DEFAULT 0", //消息收1、发0
//                @"status INTEGER NOT NULL DEFAULT 0", //文件状态：0、未使用 1、成功 2、失败
//                @"jid VARCHAR(100) NOT NULL DEFAULT ''",//联系人
//                @"content TEXT NOT NULL DEFAULT ''",
//                @"file VARCHAR(100) NOT NULL DEFAULT ''",//文件名
//                @"time DATETIME  DEFAULT (datetime('now','localtime'))",
                nil];
    }else if(IsTb(tbName,tb_dataForUser)){
        
        return [NSMutableArray arrayWithObjects:
                @"id VARCHAR(100) NOT NULL PRIMARY KEY",
                @"code DEFAULT '0'",//0自己发送的消息
                @"account DEFAULT ''",
                @"headimg DEFAULT ''",
                @"nickname DEFAULT ''",
                @"userid DEFAULT ''",
                @"content DEFAULT ''",
                @"msg DEFAULT ''",//所有数据
                @"file DEFAULT ''",//地址
                @"pid DEFAULT ''",//关联拍客id
                @"type DEFAULT '0'",//1、文字 2、图片 3、语音
                @"status DEFAULT '0'",//1已读，0未读,2同意好友，3拒绝好友申请
                @"time DEFAULT ''",
                @"localtime DATETIME  DEFAULT (datetime('now','localtime'))",
                nil];
    }else if(IsTb(tbName, tb_dataForUser)){
        return [NSMutableArray arrayWithObjects:
                @"account VARCHAR(100) NOT NULL  PRIMARY KEY",
                @"headimg DEFAULT ''",
                @"nickname DEFAULT ''",
                @"userid DEFAULT ''",
                @"sex DEFAULT ''",
                @"isfriend DEFAULT '0'",
                @"remark DEFAULT ''",
                @"time DATETIME  DEFAULT (datetime('now','localtime'))",
                nil];
    }*/
    return nil;
}
+ (SqlightAdapter*)sqlightTable:(NSString*)tbName{
    return [self sqlightDB:dbName Table:tbName];
}
+ (SqlightAdapter*)sqlightDB:(NSString*)db Table:(NSString*)tbName{
    SqlightAdapter *sqlight = [SqlightAdapter database:db AndTable:tbName];
    if (nil == sqlight) {
        sqlight = [SqlightAdapter database:db];
        NSMutableArray *marray = [self tbInfo:tbName];
        if (marray.count) {            
            SqlightResult *rlt = [sqlight createTable:tbName Info:[self tbInfo:tbName]];
            if (rlt.code == SQLITE_DONE) {
                sqlight.tableName = tbName;
                return sqlight;
            }
        }else{
            return nil;
        }
    }
    sqlight.tableName = tbName;
    return sqlight;
}
+ (NSMutableArray*)tbInfos:(NSArray*)infos key:(NSString*)key
{
    NSMutableArray *marray = [NSMutableArray array];
    for (NSString *str in infos) {
        if ([str isEqualToString:key]) {
            NSString *s = [NSString stringWithFormat:@"%@ VARCHAR(100)  PRIMARY KEY NOT NULL",str];
            [marray addObject:s];
        }else{
            [marray addObject:str];
        }
    }
    return marray;
}
+ (SqlightAdapter*)sqlightTableDB:(NSString*)db table:(NSString*)tbName tbInfo:(NSArray*)infos Pkey:(NSString*)key{
    SqlightAdapter *sqlight = [SqlightAdapter database:db AndTable:tbName];
    if (nil == sqlight) {
        sqlight = [SqlightAdapter database:db];
        SqlightResult *rlt = [sqlight createTable:tbName Info:[self tbInfos:infos key:key]];
        NSLog(@"Query Result msg:%@ code:%ld data:%@", rlt.msg, (long)rlt.code, rlt.data);
    }
    sqlight.tableName = tbName;
    return sqlight;
}
/**
 *	导入txt到数据库
 *
 *	@param	tbName	数据库表名
 *	@param	path	文件路径，留空则默认docdatapath下边 同名txt文件
 *
 *	@return	是否完全导入成功
 */

/*+ (BOOL)ImportTb:(NSString*)tbName file:(NSString*)path key:(NSString*)key
{
    NSString *str = [NSString stringWithContentsOfFile:path?path:[docDataPath stringByAppendingFormat:@"/%@.txt",tbName] encoding:NSUTF8StringEncoding error:NULL];
    NSArray *array = [str objectFromJSONString];
    if (array.count) {
        SqlightAdapter *sqlight = [self sqlightTableDB:dbName table:tbName tbInfo:[array.lastObject allKeys] Pkey:key];
        for (NSDictionary *dict in array) {
            SqlightResult *rlt = [sqlight insertData:dict];
            if(rlt.code!=101)return NO;
        }
        return YES;
    }
    return NO;
}
+ (void)ImportSyncTb:(NSString*)tbName file:(NSString*)path key:(NSString*)key
{
    NSString *str = [NSString stringWithContentsOfFile:path?path:[docDataPath stringByAppendingFormat:@"/%@.txt",tbName] encoding:NSUTF8StringEncoding error:NULL];
    NSArray *array = [str objectFromJSONString];
    if (array.count) {
        [self sqlightTableDB:dbName table:tbName tbInfo:[array.lastObject allKeys] Pkey:key];
        [self sync:tbName data:array idx:@(0) path:path?(path.lastPathComponent):tbName];
    }
}*/

+ (void)sync:(NSString*)tbName data:(NSArray*)array idx:(NSNumber*)idx path:(NSString*)file
{
//    NSDictionary * userInfo = [NSDictionary dictionaryWithObjectsAndKeys:idx,@"idx",[NSNumber numberWithInt:array.count],@"count",file,@"file",nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"importdata" object:[NSDictionary dictionaryWithObjectsAndKeys:idx,@"idx",@(array.count),@"count", nil] userInfo:nil];
    if([idx intValue]>=array.count){
    [[NSNotificationCenter defaultCenter] postNotificationName:@"importdata" object:[NSDictionary dictionaryWithObject:file forKey:@"file"] userInfo:nil];
        return;
    }
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.0 * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        
        SqlightAdapter *sqlight = [self sqlightTable:tbName];
        SqlightResult *rlt = [sqlight insertData:array[idx.intValue]];
        if (rlt.code==SQLITE_DONE) {
            [self sync:tbName data:array idx:[NSNumber numberWithInt:idx.intValue+1] path:file];
            
        }else{
            NSLog(@"%@",array[idx.intValue]);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"importdata" object:nil userInfo:nil];
        }
    });
}

/**
 *	导入array到数据库
 *
 *	@param	tbName	数据库表名
 *	@param	data	数据列表
 *  @param	KEY     创建数据库key用于，重复插入替换标识
 *	@return	是否完全导入成功
 */
+ (BOOL)ImportTb:(NSString*)tbName data:(NSArray*)array key:(NSString*)key
{
    return [self ImportDB:dbName table:tbName data:array key:key];
}
+ (BOOL)ImportDB:(NSString*)db table:(NSString*)tbName data:(NSArray*)array key:(NSString*)key
{
    SqlightAdapter *sqlight = [self sqlightTableDB:db table:tbName tbInfo:[array.lastObject allKeys] Pkey:key];
    for (NSDictionary *dict in array) {
        SqlightResult *rlt = [sqlight insertData:dict];
//        NSLog(@"Query Result msg:%@ code:%d data:%@", rlt.msg, rlt.code, rlt.data);
        if(rlt.code!=101)return NO;
    }
    return YES;
}
+ (BOOL)InsertReplace:(NSString*)tbName values:(NSDictionary*)dict{
    return [self InsertReplaceDB:dbName table:tbName values:dict];
}
+ (BOOL)InsertReplaceDB:(NSString*)db table:(NSString*)tbName values:(NSDictionary*)dict
{
    SqlightAdapter *sqlight = [self sqlightDB:db Table:tbName];
    SqlightResult *rlt = [sqlight insertData:dict];
    NSLog(@"Query Result msg:%@ code:%d data:%@", rlt.msg, rlt.code, rlt.data);
    return rlt.code==SQLITE_DONE;
}
+ (BOOL)Update:(NSString*)tbName values:(NSDictionary*)dict condition:(NSString*)con
{
    return [self UpdateDB:dbName table:tbName values:dict condition:con];
}

+ (BOOL)UpdateDB:(NSString*)db table:(NSString*)tbName values:(NSDictionary*)dict condition:(NSString*)con
{
    SqlightAdapter *sqlight = [self sqlightDB:db Table:tbName];
    SqlightResult *rlt = [sqlight updateData:dict ByCondition:con Bind:nil];
    return rlt.code==SQLITE_DONE;
}
+ (NSArray*)Select:(NSString*)tbName Filelds:(NSArray*)array condition:(NSString*)con{
    return [self SelectDB:dbName table:tbName Filelds:array condition:con];
}
+ (NSArray*)SelectDB:(NSString*)db table:(NSString*)tbName Filelds:(NSArray*)array condition:(NSString*)con
{
    SqlightAdapter *sqlight = [self sqlightDB:db Table:tbName];
    if (!array.count) {
        SqlightResult *rlt = [sqlight excuteSQL:[NSString stringWithFormat:@"PRAGMA table_info(%@)",tbName] bind:nil];
        if (rlt.code == SQLITE_DONE) {
            NSString *str = @"";
            for (NSArray *array in rlt.data) {
                str = [str stringByAppendingFormat:@"%@,",array[1]];
            }
            if(str.length)str = [str substringToIndex:str.length-1];
            array = [str componentsSeparatedByString:@","];
        }
    }
    SqlightResult *rlt = [sqlight selectFields:array ByCondition:con Bind:nil];
    if (rlt.code == SQLITE_DONE) {
        if (array.count) {
            NSMutableArray *marray = [NSMutableArray array];
            for (NSArray *item in rlt.data) {
                [marray addObject:[[NSDictionary alloc] initWithObjects:item forKeys:array]];
            }
            return marray;
        }
        return nil;
    }
    return nil;
}
+ (BOOL)Delete:(NSString*)tbName condition:(NSString*)con
{
    return [self DeleteDB:dbName table:tbName condition:con];
}
+ (BOOL)DeleteDB:(NSString*)db table:(NSString*)tbName condition:(NSString*)con
{
    SqlightAdapter *sqlight = [self sqlightDB:db Table:tbName];
    SqlightResult *rlt = [sqlight deleteByCondition:con Bind:nil];
    return rlt.code==SQLITE_DONE;
}

+ (void)excuteFile:(NSString*)path
{
    NSArray *array =[[NSString stringWithContentsOfURL:[NSURL fileURLWithPath:path] encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:@";"];
    SqlightAdapter *sqlight = [SqlightAdapter database:dbName];
    for (NSString *sql in array) {
        if ([sqlight excuteSQL:sql bind:nil].code != SQLITE_DONE) {
            continue;
        }
    }
}
+ (NSArray*)excuteSelect:(NSString*)sql Filelds:(NSArray*)array
{
    //方法需要改进，array数量不对会出错
    //完整表字段返回请使用select方法的conn查询
    SqlightAdapter *sqlight = [SqlightAdapter database:dbName];
    SqlightResult *rlt = [sqlight excuteSQL:sql bind:nil];
    if (rlt.code == SQLITE_DONE) {
        if (array.count) {
            NSMutableArray *marray = [NSMutableArray array];
            for (NSArray *item in rlt.data) {
                [marray addObject:[[NSDictionary alloc] initWithObjects:item forKeys:array]];
            }
            return marray;
        }
        return nil;
    }
    return nil;
}
@end
